import xlrd
from TestToolsV2.common.ChackStr import chackStr


class reader:
    def __init__(self):
        self.headers = None
        self.idDict = {}
        self.nameDict = {}
        self.idNameDict = {}
        self.isResourceList = []
        self.eInfo = None
        self.path = None

    def ReadBase(self, path, idIndex=0, nameIndex=1, hasName=False, sheetIndex=0):
        """
        读取Excel表格，读取到的数据储存在以ID为索引和以名字为索引的字典中\n
        :param path: 表格绝对路径
        :param sheetIndex: 读取的sheet索引
        :param idIndex: id的索引（id在表格的第几列,索引从0开始）
        :param nameIndex: 名字的索引（名字在表格的第几列,索引从0开始）
        :param hasName: 是否具备名字索引，默认不使用名字索引
        :return: 读取成功返回true，否则返回false，错误信息储存在eInfo中
        """
        titel = "reader => ReadBase: "
        try:
            sheets = xlrd.open_workbook(path)
        except FileNotFoundError:
            self.eInfo = f"{titel}文件路径错误\n{path}"
            return False
        else:
            sheet = sheets.sheet_by_index(sheetIndex)
            nrows = sheet.nrows
            isResource_index = None
            if nrows > 2:
                for r in range(nrows):
                    if r == 2:
                        self.headers = sheet.row_values(rowx=r)
                        if "isResource" in self.headers:
                            isResource_index = self.headers.index("isResource")
                            # print(self.headers)
                    if r > 2:
                        rowItem = sheet.row_values(rowx=r)
                        dataList = self.SetList(rowItem)
                        self.idDict[dataList[idIndex]] = dataList
                        if hasName:
                            self.nameDict[dataList[nameIndex]] = dataList
                            self.idNameDict[dataList[idIndex]] = dataList[nameIndex]
                        if isResource_index:
                            if dataList[isResource_index] == "1":
                                self.isResourceList.append(dataList[idIndex])
                                # print(dataList[idIndex])
                self.path = path
                return True
            else:
                self.eInfo = f"{titel}文件中无内容"
                return False

    def GetName(self, Id):
        return self.idNameDict.get(Id, 'None')

    def GetId(self, name):
        for key, value in self.idNameDict:
            if name == value:
                return key

    @staticmethod
    def SetList(dataList):
        """
        将列表中的数字内容进行过滤\n
        :param dataList: 需要过滤的列表
        :return: 返回一个将数字过滤为字符串的元组
        """
        tempList = []
        for item in dataList:
            item = chackStr.ToStr(item)
            tempList.append(item)
        return tuple(tempList)

    def GetDataList(self, searchList, by="1"):
        """
        获取普通数据，返回数据列表\n
        :param searchList: 需要搜索的列表
        :param by: 搜索类型，1为ID，0为中文名
        :return: 返回搜索结果(tuple)
        """
        # Log.LogShow(searchList, 40, "GetDataList")
        if not self.path:
            return None

        if searchList:
            dataList = []
            if by == "1":
                myDict = self.idDict
            else:
                myDict = self.nameDict

            for i in range(len(searchList)):
                if i > 0:
                    if searchList[i]:
                        if searchList[i] in myDict:
                            dataList.append(myDict[searchList[i]])
                            # Log.LogShow(f"1. {type(myDict[item])} -> {myDict[item]}", 20, "GetDataList")
                        else:
                            dataList.append(f"[{searchList[i]}] 查无数据")
                            # Log.LogShow(f"2. {type(item)} -> {item}", 30, "GetDataList")

            return tuple(dataList)
        else:
            return None

    def GetActivityList(self, searchList):
        """
        获取活动数据，放回数据列表\n
        :param searchList: 需要搜索的二维列表
        :return: 返回二维元组数据((n,i,t,c),(n,i,t,c)...)
        """
        if not self.path:
            return None

        if searchList:
            activityList = []
            for dataList in searchList:
                tempList = []
                if dataList:
                    for data in dataList:
                        item = data.split(',')
                        if item[1] in self.idDict:
                            name = self.idDict[item[1]][2]
                            tempList.append(f"{item[0]}, {name}, {item[2]}")
                        else:
                            tempList.append(f">>>>[ {item[1]} ]查无数据<<<<")

                activityList.append(tuple(tempList))
            return tuple(activityList)
        else:
            return None

    def IsResource(self, itemID):
        """
        通过道具ID判断道具是否为10类型
        :param itemID: 道具ID
        :return: 是资源类型返回True
        """
        if itemID in self.isResourceList:
            return True
        else:
            return False
